<template>
  <div id="header">
    <!-- 左侧logo -->
    <div class="header-logo pointer" @click="goHome">
      <!-- <a-icon class="logo-wangyiyun" type="icon-wangyiyunyinle" /> -->
      <i class="iconfont icon-wangyiyunyinle"></i>
    </div>
    <!-- 回退、前进按钮 -->
    <div class="btn-list">
      <div @click="goOrBack('left')" class="left">
        <a-icon class="prev-btn" type="left" />
      </div>
      <div @click="goOrBack('right')" class="right">
        <a-icon class="next-btn" type="right" />
      </div>
    </div>
    <!-- 搜索框 -->
    <div class="search-input">
      <a-input-search
        allowClear
        placeholder="请搜索"
        style="width: 200px"
        v-model="searchValue"
        @search="searchWord"
        @change="changeValue"
        @click="showSearchDetail"
      />
      <transition name="el-fade-in">
        <div class="search-tooltip" v-show="isSearch">
          <!-- <transition name="el-fade-in"> -->
            <Search
              v-if="!showDream"
              :searchList="searchList"
              :historyList="searchHistory"
              @searchWord="searchWord"
              @searchHistory="searchWord"
              @delete="removeHistory"
              @deleteOne="deleteOne"
            />
            <a-skeleton
              v-else
              active
              :loading="showSkeleton"
            >
              <SearchInfo
                v-for="item in searchDream.order"
                :key="item"
                :skeleton="showSkeleton"
                :searchTitle="item"
                :typeList="searchDream[item]"
                @change="id => goOrPlay(item, id)"
                @goTypeDetail="goTypeDetail"
              >
                <template slot-scope="scope">
                  <span>{{ scope.dreamItem.name }}</span>
                  <span v-if="item === 'albums'">
                    - {{ scope.dreamItem.artist.name }}
                  </span>
                  <span v-if="item === 'songs'">
                    - {{ scope.dreamItem.artists[0].name }}
                  </span>
                </template>
              </SearchInfo>
            </a-skeleton>
          <!-- </transition> -->
        </div>
      </transition>
      <div class="mask" v-show="isSearch" @click="isSearch = false"></div>
    </div>
    <!-- 登录状态、头像 -->
    <div class="header-info">
      <a-avatar class="pointer" v-if="!isLogin" icon="user" @click="showM"></a-avatar>
      <img class="pointer" v-else v-lazy="user.avatarUrl" @click="goDetail">
      <span class="login-state" @click="goDetail">{{ isLogin ? user.nickname : '未登录' }}</span>
    </div>

    <!-- 登录弹框 -->
    <a-modal
      ref="modal"
      showOk="none"
      showNo="none"
      :getContainer="getDOM"
      :visible="showModal"
      @onCancel="cancel"
    >
      <template #content>
        <!-- 扫码登录 -->
        <div class="qr-codes">
          <div class="qr-title font-weight font-24">扫码登录</div>
          <div class="qr-img">
            <img :src="qrBase" alt="">
            <div class="mask-qr" ref="maskQr">
              <div class="qr-text mbottom-10">二维码已失效</div>
              <a-button type="primary" @click="goLogin()">点击刷新</a-button>
            </div>
          </div>
          <div class="qr-caution mtop-20">
            打开<a href="https://music.163.com/#/download">网易云音乐手机端</a>扫码登录
          </div>
          <div class="qr-otherLogin pointer" @click="loginType">
            选择其他登录模式
            <a-icon type="right" />
          </div>
        </div>
        <div class="other-login" style="display: none;">
          <Tabs :tabList="tabList" @target="target" />
          <div class="qr-examp pointer" @click="loginType">
            <div class="triangle"></div>
            <img class="img-percent" :src="qrBase">
          </div>
          <div>开发中...</div>
          <!-- 手机登录 -->
          <!-- <div class="phone-login">
            <a-form-model
              ref="loginForm"
              layout="vertical"
              :model="loginForm"
              :rules="rules"
              :hideRequiredMark="true"
            >
              <a-form-model-item ref="telPhone" label="手机号" prop="phoneRules">
                <a-input
                  size="large"
                  v-enter-number
                  v-model="loginForm.telPhone"
                  placeholder="请输入手机号"
                >
                  <a-icon slot="prefix" type="mobile" style="color: rgba(0,0,0,.25)" />
                </a-input>
              </a-form-model-item>
              <a-form-model-item ref="password" label="密码" prop="passRules">
                <a-input-password
                  size="large"
                  v-model="loginForm.password"
                  placeholder="请输入密码"
                >
                  <a-icon slot="prefix" type="lock" style="color: rgba(0,0,0,.25)" />
                </a-input-password>
              </a-form-model-item>
              <a-form-model-item
                ref="verificationCode"
                style="display: none;"
                label="验证码"
                prop="verRules"
              >
                <a-input
                  size="large"
                  style="width: 200px;"
                  v-model="loginForm.verificationCode"
                  placeholder="请输入验证码"
                ></a-input>
                <a-button size="large" class="mleft-10">获取验证码</a-button>
              </a-form-model-item>
              <a-form-model-item>
                <a-button
                  html-type="submit"
                  class="login-form-button"
                  @click="onSubmit"
                >
                  登录
                </a-button>
              </a-form-model-item>
            </a-form-model>
          </div> -->
        </div>
      </template>
    </a-modal>

    <!-- 退出登录弹框 -->
    <a-modal
      :visible="visibleLogout"
      @onOk="onOk"
      @onCancel="cancel"
    >
      <template #title>
        <span>提示</span>
      </template>
      <template #content>
        <span>将要退出登录,是否继续?</span>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import {
  Avatar, Input, Skeleton
} from 'ant-design-vue';
import { debounce } from '@/utils/optimize';
import Modal from '@/components/Library/Modal';
import Tabs from '@/components/Content/Tabs';
import Search from '@/components/Detail/Search';
import SearchInfo from '@/components/Detail/Search/searchInfo';
import { searchDetail, searchSuggest } from '@/api/detail';
import { morePlayDetail } from '@/api';
import {
  qrKey, qrCreate, qrCheck, userInfo, logout
} from '@/api/login';

export default {
  name: 'Header',

  inject: ['reload'],

  components: {
    Tabs,
    Search,
    SearchInfo,
    ASkeleton: Skeleton,
    // AFormModel: FormModel,
    // AFormModelItem: FormModel.Item,
    AModal: Modal,
    // AInput: Input,
    // AInputPassword: Input.Password,
    AAvatar: Avatar,
    AInputSearch: Input.Search,
  },

  data() {
    let validatePass = (rule, value, callback) => {
      console.log(rule,value)
      if (value.trim() === '') {
        callback(new Error('请输入手机号'));
      } else {
        const reg = /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/;
        if (this.loginForm.telPhone.trim() !== '' && reg.test(value)) {
          this.$refs.ruleForm.validateField('checkPass');
          callback();
        } else {
          callback(new Error('手机号输入有误,请重新填写'))
        }
      }
    };
    return {
      // 显示登录弹框
      // showModal: false,
      // 显示退出登录弹框
      visibleLogout: false,
      // 定时器标识
      check: null,
      // 二维码base64
      qrBase: '',
      tabList: [{
        tabName: '密码',
        isActive: true,
        id: 'password'
      }, {
        tabName: '验证码',
        isActive: false,
        id: 'authCode'
      }],
      // 表单数据收集
      loginForm: {
        telPhone: undefined,
        passowrd: undefined,
        verificationCode: undefined
      },
      // 验证规则
      rules: {
        phoneRules: [
          { validate: validatePass, trigger: 'change' },
          // { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
        ],
        passRules: [{ required: true, message: '请输入密码', trigger: 'change' }],
        verRules: [{ required: true, message: '请输入验证码', trigger: 'change' }],
      },
      // 存储用户信息
      user: {},
      // 搜索列表
      searchList: [],
      // 搜索历史
      searchHistory: [],
      // 搜索联想信息
      searchDream: {},
      // 显示隐藏搜索框
      isSearch: false,
      // 是否显示联想组件
      showDream: false,
      searchValue: '',
      // 是否显示联想信息骨架屏
      showSkeleton: true
    };
  },

  mounted() {
    // 刷新页面重载时,如有当前登录人信息,取出来重新渲染
    this.user = JSON.parse(localStorage.getItem('userInfo'));
    if (this.user && Object.keys(this.user).length) {
      // 给vuex中的userInfo重新赋值
      this.$store.commit('detail/USERINFO', this.user);
    }
    // 搜索历史记录
    const history = JSON.parse(localStorage.getItem('history'));
    if (history && history.length) this.searchHistory = history;
  },

  computed: {
    isLogin() {
      return this.user && this.user.userId
    },
    searchlist() {
      return this.searchList && this.searchList.length
    },
    ...mapState({
      showModal: state => state.main.showModal
    })
  },

  watch: {
    showModal: {
      handler(value) {
        if (value) this.goLogin();
      },
      // immediate: true
    }
  },

  methods: {
    onSearch() {},
    getDOM() {
      return document.querySelector('#header');
    },
    async showSearchDetail() {
      this.isSearch = true;
      if (this.searchlist) return; 
      const res = (await searchDetail()).data;
      this.searchList = Object.freeze(res.data);
    },
    searchWord(key) {
      // 如果没有搜索值不进行后续跳转
      if (!key) return;
      this.searchValue = key;
      // 搜索联想组件隐藏
      this.showDream = false;
      // 记录搜索历史
      this.searchHistory.unshift({
        id: new Date().getTime(),
        name: key
      });
      // 搜索历史去重
      const newObj = {};
      this.searchHistory = this.searchHistory.reduce((preVal, curVal) => {
        newObj[curVal.name] ? '' : newObj[curVal.name] = preVal.push(curVal); 
        return preVal;
      }, []);
      // 持久化搜索记录
      localStorage.setItem('history', JSON.stringify(this.searchHistory));
      this.$router.push({
        name: 'searchdetail',
        query: {
          keywords: key
        }
      });
      // 整个搜索框隐藏
      this.isSearch = false;
      // 点击跳转也需要进行联想搜索
      this.changeValue();
    },
    changeValue: debounce(async function(e) {
      const value =
        e && e.target ? e.target.value : this.searchValue ;
      if (!value) {
        this.showDream = false;
        return;
      }
      this.showDream = this.showSkeleton = true;
      const res = (await searchSuggest(value)).data;
      this.searchDream = Object.freeze(res.result);
      this.showSkeleton = false;
    }, 500),
    // 联想后点击标题跳转到对应的详情
    goTypeDetail(name) {
      this.$store.commit('main/OPERATION', {
        current: name === '单曲' ? 0 : name === '歌手' ? 1 : name === '专辑' ? 2 : 4,
        page: 1
      });
      this.$router.push({
        name: 'searchdetail',
        query: {
          keywords: this.searchValue
        }
      })
      this.isSearch = false;
    },
    removeHistory() {
      this.searchHistory = [];
      localStorage.removeItem('history');
    },
    // 删除当前tag标签
    deleteOne(id) {
      const index = this.searchHistory.findIndex(item => item.id === id);
      this.searchHistory.splice(index, 1);
      // 持久化搜索记录
      localStorage.setItem('history', JSON.stringify(this.searchHistory));
    },
    async goOrPlay(item, id) {
      const o = { name: '', query: { id } };
      if (item === 'songs') {
        const res = (await morePlayDetail(id)).data;
        this.$store.commit('main/ISPLAYED', true);
        this.$store.commit('detail/AUDIOID', res.songs[0]);
        this.$store.commit('detail/ADDAUDIOLIST', res.songs[0]);
      } else {
        if (item === 'artists') {
          o.name = 'artistdetail';
        } else if (item === 'albums') {
          o.name = 'albumdetail';
        } else {
          o.name = 'playlistdetail';
        }
        this.$router.push(o);
      }
      this.isSearch = false;
    },
    showM() {
      this.$store.commit('main/SHOWMODAL', true);
    },
    // 点击登录弹框
    async goLogin() {
      // 获取二维码key
      const key = (await qrKey()).data.data.unikey;
      this.qrBase = (await qrCreate(key)).data.data.qrimg;
      // this.$store.dispatch('main/getqrCode');
      // 需要注意,必须等待接口生成二维码后再显示modal,避免弹框已经出来了无法渲染出二维码
      if (this.qrBase) {
        // this.showModal = true;
        this.$store.commit('main/SHOWMODAL', true);
      }
      // 800为二维码过期,801为等待扫码,802为待确认,803为授权登录成功
			// 每5秒check一次
      this.check = setInterval(async () => {
        let res = await qrCheck(key);
        switch(res.data.code) {
          case 800:
            // 显示遮罩层
            this.$refs.maskQr.style.display = 'flex';
            clearInterval(this.check);
            break;
          case 801:
            if (this.$refs.maskQr.style.display === 'flex') {
              // 如果遮罩层显示才需要隐藏
              this.$refs.maskQr.style.display = 'none';
            }
            break;
          case 803:
            this.getUserInfo();
            break;
          default:
            this.$message.loading('登录中,请稍等...', 10);
        }
      }, 2000);
    },
    // 登录弹框关闭事件
    cancel() {
      // this.showModal = false;
      this.$store.commit('main/SHOWMODAL', false);
      this.visibleLogout = false;
      // 关闭弹框时需要清除定时器,停止调用扫码接口
      if (this.check) clearInterval(this.check);
    },
    // 弹框确认事件
    async onOk() {
      await logout();
      this.$message.success('退出登录成功');
      localStorage.removeItem('userInfo');
      // 清空播放歌曲
      localStorage.removeItem('currentSong');
      localStorage.removeItem('recentPlay');
      localStorage.removeItem('userPlayList');
      // 清空用户侧边栏列表
      this.$store.commit('detail/USERPLAYLIST', []);
      // 重定向回首页
      // if (this.$route.name === 'recommendation') {
      //   this.reload();
      //   return;
      // }
      this.reload();
      this.$router.push({
        name: 'recommendation'
      });
    },
    // 获取用户信息
    async getUserInfo() {
      const res = await userInfo();
      this.user = res.data.profile;
      // 将登录用户信息存放在vuex中
      this.$store.commit('detail/USERINFO', res.data.profile);
      this.$message.success(`登录成功,${this.user.nickname}`);
      this.$store.dispatch('detail/getResource');
      // 获取登录人创建收藏列表
      this.$store.dispatch('detail/getPlayListU', {
        uid: res.data.profile.userId,
        // limit: 20,
        // offset: 0,
        timestamp: new Date().getTime()
      });
      // 登录成功清除定时器
      clearInterval(this.check);
      this.$refs.modal.closeModal();
    },
    // 点击跳转用户详情页
    goDetail(event) {
      const { innerHTML } = event.target;
      console.log(innerHTML);
      if (!innerHTML) {
        this.$router.push({
          name: 'userdetail',
          query: {
            id: this.user.userId
          }
        });
      } else {
        if (innerHTML !== '未登录') {
          this.visibleLogout = true;
        }
      }
    },
    // 点击登录时验证
    onSubmit() {
      this.$refs.loginForm.validate(valid => {
        console.log(valid)
        if (valid) {
          alert('submit!');
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 以哪种登录方式显示
    loginType(event) {
      console.log(event);
      const typeClass = event.target.classList[0];
      // 用v-if或v-show都不可以，只能通过操作DOM了
      const qr = document.querySelector('.qr-codes');
      const other = document.querySelector('.other-login');
      switch(typeClass) {
        case 'qr-otherLogin':
          other.style.display = 'block';
          qr.style.display = 'none';
          break;
        default:
          other.style.display = 'none';
          qr.style.display = 'flex';
      }
    },
    // 切换tab时,以密码登录还是验证码登录
    target(name) {
      switch (name) {
        case 'password':
          this.$refs.password.$el.style.display = 'block';
          this.$refs.verificationCode.$el.style.display = 'none';
          break;
        default:
          this.$refs.password.$el.style.display = 'none';
          this.$refs.verificationCode.$el.style.display = 'block';
      }
    },
    // 历史操作回退
    goOrBack:  debounce(function(type) {
      switch(type) {
        case 'left':
          // this.$router.go(-1);
          this.$router.back();
          break;
        default:
          this.$router.go(1);
      }
      // const active = sessionStorage.getItem('asideActive');
      // if (active) this.$eventBus.$emit('preAside');
    }, 300),
    // 返回首页
    goHome() {
      this.$router.push({
        name: 'recommendation'
      })
    }
  }
};
</script>

<style lang="less" scoped>
#header {
  display: flex;
  width: 100%;
  height: 100%;
  color: #fff;
  align-items: center;
  .header-logo {
    height: 100%;
    .iconfont {
      font-size: 30px !important;
    }
  }
  .btn-list {
    display: flex;
    justify-items: flex-end;
    align-items: center;
    margin-left: 100px;
    height: 100%;
    .left, .right {
      background: #e13e3e;
      border-radius: 50%;
      width: 25px;
      height: 25px;
      display: flex;
      justify-content: center;
      align-items: center;
      line-height: 60px;
      cursor: pointer;
    }
    .left {
      margin-right: 6px;
    }
  }
  .search-input {
    position: relative;
    height: 100%;
    margin-left: 25px;
    /deep/input.ant-input {
      border-radius: 20px;
      background: #e13e3e;
      height: 36px;
      line-height: 36px;
      border: none;
      color: #fff;
      box-shadow: none;
    }
    /deep/span.ant-input-suffix {
      // left: 12px;
      // right: auto;
      > i {
        // font-size: 22px;
        color: #fff;
        font-weight: 600;
      }
    }
    .search-tooltip {
      position: absolute;
      top: 55px;
      left: 0;
      width: 340px;
      min-height: 340px;
      max-height: 420px;
      transition: all .5s;
      overflow-y: auto;
      border-radius: 8px;
      box-shadow: 0 1px 4px #ddd;
      background-color: #fff;
      z-index: 100;
      color: #000;
      /deep/h3.ant-skeleton-title {
        margin-left: 10px;
      }
      /deep/ul.ant-skeleton-paragraph {
        margin: 0 20px;
      }
    }
    .mask {
      position: fixed;
      top: 0;
      left: 0;
      bottom: 0;
      width: 100%;
      height: 100%;
      right: 0;
    }
  }
  .header-info {
    display: flex;
    align-items: center;
    height: 100%;
    >img {
      width: 30px;
      height: 30px;
      border-radius: 50%;
    }
    >span {
      margin-left: 10px;
    }
  }
  /deep/.ant-modal-content {
    height: calc(100vh - 215px);
  }
  .qr-codes {
    position: relative;
    width: 100%;
    height: calc(100vh - 265px);
    display: flex;
    flex-direction: column;
    align-items: center;
    .qr-title {
      color: #000;
    }
    a {
      text-decoration: none;
    }
    .qr-img {
      position: relative;
      .mask-qr {
        width: 100%;
        height: 100%;
        display: none;
        position: absolute;
        top: 0;
        background: rgba(0, 0, 0, 0.7);
        flex-direction: column;
        justify-content: center;
        align-items: center;
        color: #fff;
        .ant-btn:hover,
        .ant-btn:focus {
          color: #fff;
          border-color: #40a9ff;
        }
      }
    }
    .qr-otherLogin {
      position: absolute;
      bottom: 100px;
    }
  }
  /deep/div#content-tab {
    position: relative;
    z-index: 999;
  }
  /deep/ul.tab-list {
    margin-left: 20px !important;
  }
  /deep/input.ant-input:hover {
    border-color: #ec4141;
  }
  .phone-login {
    padding: 0 30px;
    .login-form-button {
      width: 100%;
      height: 50px;
      background-color: #ec4141;
      color: #fff;
      text-align: center;
      border-radius: 10px;
      font-size: 20px;
    }
  }
  .qr-examp {
    position: absolute;
    top: 0;
    left: 0;
    width: 50px;
    height: 50px;
    .triangle {
      position: absolute;
      top: 17px;
      left: 17px;
      border: 35px solid transparent;
      border-bottom: 35px solid #fff;
      transform: rotate(135deg);
    }
  }
}
</style>